package org.freemarker.core.dao.impl;

import java.util.List;

import javax.persistence.Query;

import org.freemarker.core.dao.CarDao;
import org.freemarker.core.model.Car;
import org.springframework.stereotype.Repository;

@Repository
public class CarDaoImpl extends EntityJpaDaoImpl<Car> implements CarDao {

	public CarDaoImpl() {
		setClazz(Car.class);
	}

	@Override
	public long getNumberOfCarsForNr(String nrMatricol) {
		Query q = super.entityManager.createQuery("SELECT count(*) FROM "
				+ clazz.getName() + " c WHERE c.numar_matricol=" + "'" + nrMatricol + "'");
		List<?> resultList = q.getResultList();

		return Long.valueOf(resultList.size());
	}


	@Override
	public Car getCarForNr(String nrMatricol) {
		Query q = super.entityManager.createQuery("FROM "
				+ clazz.getName() + " WHERE numar_matricol=" + "'" + nrMatricol + "'");
		Car result = (Car) q.getSingleResult();

		return result;
	}
	
	public List<Car> findNotUsed(){
		@SuppressWarnings("unchecked")
		List<Car> resultList = entityManager.createQuery("FROM "
														+ clazz.getName() + " where contact_id=null").getResultList();
		return resultList;
	}

	@Override
	public Car getCarForContact(long id) {
		Query q = super.entityManager.createQuery("FROM "
				+ clazz.getName() + " WHERE contact_id='" +  id +"'");
		Car result = (Car) q.getSingleResult();

		return result;
	}
	
	@Override
	public void setNotUsed(long id){
		Query q = super.entityManager.createQuery("UPDATE "
				+ clazz.getName() + " SET contact_id=NULL WHERE contact_id=" +  id );
		q.executeUpdate();

	}

	@Override
	public List<Car> getByBrand(String brand) {
		@SuppressWarnings("unchecked")
		List<Car> resultList = entityManager.createQuery("FROM "
														+ clazz.getName() + " where marca='" +brand+ "'" ).getResultList();
		return resultList;
	}


	
}
